package com.aim.Service;

import java.io.File;
import java.util.ArrayList;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.aim.Activity.ImpoundTab;
import com.aim.api.AIMCaseConstants;
import com.aim.util.DBAdapter;
import com.aim.util.FileUploader;
import com.aim.util.KeyAndValuePair;
import com.aim.util.WebServiceUtil;

public class UploadLocalService extends Service {
	private static final String TAG = "UploadLocalService";
	private NotificationManager _nm;
	DBAdapter mDBAdapter;
	int picNo;
	String caseNo;
	
	private Handler handler = new Handler(){  
  	  
        @Override  
        public void handleMessage(Message msg) {  
              
        	if(msg.what ==1)
            {

	         	Toast.makeText(getApplicationContext(), "Local impounds automatically uploaded to website, please fresh your impoundlist", Toast.LENGTH_LONG).show();
            }
        	}
        };
	
	@Override
	public IBinder onBind(Intent i) {
	Log.e(TAG, "============> TestService.onBind");
	return null;
	}

	public class LocalBinder extends Binder {
	public UploadLocalService getService() {
	return UploadLocalService.this;
	}
	}

	@Override
	public boolean onUnbind(Intent i) {
	Log.e(TAG, "============> TestService.onUnbind");
	return false;
	}

	@Override
	public void onRebind(Intent i) {
	Log.e(TAG, "============> TestService.onRebind");
	}

	@Override
	public void onCreate() {
	Log.e(TAG, "============> TestService.onCreate");
	
	mDBAdapter = new DBAdapter(this);
	_nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
	
	}

	@Override
	public void onStart(Intent intent, int startId) {
	Log.e(TAG, "============> TestService.onStart");
	
//	Toast.makeText(getApplicationContext(), "start", Toast.LENGTH_LONG);
	
	Thread a =
		new Thread(){  
    		  
            @Override  
            public void run() {
            	

                while(true){
            	try { 
            		
					Thread.sleep(300000);
					
				} catch (InterruptedException e) {

					e.printStackTrace();
				}
				
				

				
				 //NETWORK DETECTION
		        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		        NetworkInfo netInfo = cm.getActiveNetworkInfo();
//		        NetworkInfo netInfo = cm.getNetworkInfo(0);				        

		        if (netInfo != null && netInfo.isConnected()){
		        	uploadLocalCases();
		        }
		        else{
		        	 Log.e("Net info", "Not Connected");
		        }
				
                }
            }};
            a.start(); 

        	
//	onDestroy(); 
	}

	@Override
	public void onDestroy() {
		
	_nm.cancel(null, 0);
	Log.e(TAG, "============> TestService.onDestroy");
	}
	
	private void uploadLocalCases(){
		
		mDBAdapter.open();
		Cursor c = null;
		try {
			c = mDBAdapter.fetchAllLocalCases();
			while(!c.isAfterLast()){
//			Map<String, Object> map = new HashMap<String, Object>();
			String no="Local"+c.getInt(0);
			String vin=c.getString(1);
			String make=c.getString(2);
			String model=c.getString(3);
			String color=c.getString(4);
			String type=c.getString(5);
			String year=c.getString(6);
			String plate=c.getString(7);
			String mileage=c.getString(8);
			String add=c.getString(9);
			String city=c.getString(10);
			String state=c.getString(11);
			String zip=c.getString(12);
			String tow=c.getString(13);
			int bookmark= Integer.parseInt(c.getString(14));
			String title=c.getString(15);
			String note=c.getString(16);

//			map.put("noteNo","0");
			caseNo = createCase(make,model,color,type,year,vin, add,city,state,zip, tow,mileage,plate,bookmark,note,title);
			
			if(!caseNo.equals("0"))
					{
				
				handler.sendEmptyMessage(1);
				for(int i =1; i<=ImpoundTab.LIMIT; i++)
			
        	{ 
        		String picname= AIMCaseConstants.SAVEDDIRECTORY+no+"img"+i+".jpg";
        	    File mF = new File(picname);
        	    if(mF.exists())
        	    { 
        	    	uploadImage(i,no);
        	    	mF.delete();
        	    }
        	 
        	}
			int index = c.getInt(0);
			mDBAdapter.deleteCase(index);
			}
			c.moveToNext();
			}
			c.close();
			
	}catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		if(c!=null)
			c.close();
	}
	mDBAdapter.close();
	}
	private void uploadImage(int i, String no) {
		String pictureFileName = AIMCaseConstants.SAVEDDIRECTORY+no+"img"+i+".jpg";
		FileUploader uploader = new FileUploader();
		File f = new File(pictureFileName);
		if (f.exists())
		{
			boolean result = uploader.doFileUpload(pictureFileName, caseNo);
		if (result) {

			Log.e("success",pictureFileName);
		
		} else {

			Log.e("fail",pictureFileName);
		
		}
		}
		
//		Log.e("picNo", ShowPhotos.picNo+"");
	}
    public String createCase(String make, String model, String color, String type, 
    		String year, String vin, String add, String city, String state, String zip, 
    		String tow, String mileage, String plate, int bookmark , String note, String title){

		ArrayList parameterList = new ArrayList();
		
		KeyAndValuePair pictureCountPair = new KeyAndValuePair();
		pictureCountPair.setKeyName("howmanyPicture");
		pictureCountPair.setKeyValue("0");
		parameterList.add(0, pictureCountPair);

		KeyAndValuePair carMakePair = new KeyAndValuePair();
		carMakePair.setKeyName("carMake");
		carMakePair.setKeyValue(make);
		parameterList.add(1, carMakePair);

		KeyAndValuePair carModelPair = new KeyAndValuePair();
		carModelPair.setKeyName("carModel");
		carModelPair.setKeyValue(model);
		parameterList.add(2, carModelPair);

		KeyAndValuePair carColorPair = new KeyAndValuePair();
		carColorPair.setKeyName("carColor");
		carColorPair.setKeyValue(color);
		parameterList.add(3, carColorPair);

		KeyAndValuePair carTypePair = new KeyAndValuePair();
		carTypePair.setKeyName("carType");
		carTypePair.setKeyValue(type);
		parameterList.add(4, carTypePair);
		
		KeyAndValuePair carYearPair = new KeyAndValuePair();
		carYearPair.setKeyName("carYear");
		carYearPair.setKeyValue(year);
		parameterList.add(5, carYearPair);

		KeyAndValuePair vinPair = new KeyAndValuePair();
		vinPair.setKeyName("vin");
		vinPair.setKeyValue(vin);
		parameterList.add(6, vinPair);

		KeyAndValuePair addressPair = new KeyAndValuePair();
		addressPair.setKeyName("address");
		addressPair.setKeyValue(add);
		parameterList.add(7, addressPair);
		
		KeyAndValuePair cityPair = new KeyAndValuePair();
		cityPair.setKeyName("city");
		cityPair.setKeyValue(city);
		parameterList.add(8, cityPair);
		
		KeyAndValuePair statePair = new KeyAndValuePair();
		statePair.setKeyName("state");
		statePair.setKeyValue(state);
		parameterList.add(9, statePair);
		
		KeyAndValuePair zipPair = new KeyAndValuePair();
		zipPair.setKeyName("zip");
		zipPair.setKeyValue(zip);
		parameterList.add(10, zipPair);

		KeyAndValuePair towReasonPair = new KeyAndValuePair();
		towReasonPair.setKeyName("towReason");
		towReasonPair.setKeyValue(tow);
		parameterList.add(11, towReasonPair);

		KeyAndValuePair mileagePair = new KeyAndValuePair();
		mileagePair.setKeyName("mileage");
		mileagePair.setKeyValue(mileage);
		parameterList.add(12, mileagePair);

		KeyAndValuePair licensePlatePair = new KeyAndValuePair();
		licensePlatePair.setKeyName("licensePlate");
		licensePlatePair.setKeyValue(plate);
		parameterList.add(13, licensePlatePair);
	
		KeyAndValuePair bookmarkPair = new KeyAndValuePair();
		bookmarkPair.setKeyName("bookmark");
		String b = "false";
		if (bookmark==1) b = "true";
		bookmarkPair.setKeyValue(b);
		parameterList.add(14, bookmarkPair);
		
		KeyAndValuePair notetitlePair = new KeyAndValuePair();
		notetitlePair.setKeyName("notetitle");
		notetitlePair.setKeyValue(title);
		parameterList.add(15, notetitlePair);
		
		KeyAndValuePair notePair = new KeyAndValuePair();
		notePair.setKeyName("note");
		notePair.setKeyValue(note);
		parameterList.add(16, notePair);


		String resultno = WebServiceUtil.callWebservice(
				"createNewCaseBean", parameterList);
						
				return resultno;												


}
	}